package org.darkforest.common.services.impl;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.darkforest.common.services.HealthUserService;
import org.darkforest.common.services.MessageAndNoticeService;
import org.darkforest.common.util.CalculateUserAgeUtils;
import org.darkforest.common.util.DateUtil;
import org.darkforest.dao.mapper.HealthCycleMapper;
import org.darkforest.dao.mapper.HealthOrgAppointmentMapper;
import org.darkforest.dao.mapper.HealthOrgMapper;
import org.darkforest.dao.mapper.HealthUserAppointmentMapper;
import org.darkforest.dao.mapper.HealthUserMapper;
import org.darkforest.dao.mapper.MemberMsgTplMapper;
import org.darkforest.model.HealthCycle;
import org.darkforest.model.HealthOrg;
import org.darkforest.model.HealthOrgAppointment;
import org.darkforest.model.HealthUser;
import org.darkforest.model.HealthUserAppointment;
import org.darkforest.model.MemberMsgTpl;
import org.darkforest.vo.AjaxReturnData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

@Service
public class HealthUserServiceImpl implements HealthUserService {

    Logger logger = LoggerFactory.getLogger(HealthUserServiceImpl.class);

    @Autowired
    private HealthUserMapper healthUserMapper;
    @Autowired
    private HealthUserAppointmentMapper userAppointmentMapper;
    @Autowired
    private HealthOrgMapper healthOrgMapper;
    @Autowired
    private HealthOrgAppointmentMapper appointmentMapper;
    @Autowired
    private HealthCycleMapper healthCycleMapper;
    @Autowired
    private MemberMsgTplMapper memberMsgTplMapper;
    @Autowired
    private MessageAndNoticeService messageAndNoticeService;

    @Override
    @Transactional
    public AjaxReturnData addHealthUserList(List<HealthUser> healthUserList) {
        AjaxReturnData ajaxReturnData = new AjaxReturnData();

        HealthUser healthUser = null;
        for (int i = 0; i<healthUserList.size(); i++) {
            healthUser = healthUserList.get(i);

            // 手机号相同数据CHECK
            HealthUser checkMobPhone = new  HealthUser();
            checkMobPhone.setMobPhone(healthUser.getMobPhone());
            checkMobPhone.setPageSwitch(false);
            List<HealthUser> searchedList = healthUserMapper.selectListByCondition(checkMobPhone);
            // 手机号相同的数据没有
            if ((searchedList == null) || (searchedList.size() == 0)) {
                // 不处理
            } else {
                // 数据库内有重复数据
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                ajaxReturnData.setResult(false);
                ajaxReturnData.setMessage("手机号为"+healthUser.getMobPhone()+"的用户信息已存在！");
                return ajaxReturnData;
            }

            // 身份证号相同数据CHECK
            HealthUser checkCardId = new  HealthUser();
            checkCardId.setCardId(healthUser.getCardId());
            checkCardId.setPageSwitch(false);
            List<HealthUser> cardIdCheckList = healthUserMapper.selectListByCondition(checkCardId);
            // 身份证号相同的数据没有
            if (cardIdCheckList == null || cardIdCheckList.size() == 0) {
                // 不处理
            } else {
                // 数据库内有重复数据
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                ajaxReturnData.setResult(false);
                ajaxReturnData.setMessage("身份证号为"+healthUser.getCardId()+"的用户信息已存在！");
                return ajaxReturnData;
            }

            healthUserMapper.insertSelective(healthUser);
        }

        ajaxReturnData.setResult(true);
        ajaxReturnData.setMessage("导入成功");

        return ajaxReturnData;
    }

    @Override
    public AjaxReturnData appointmentCheckup(HealthUser healthUserRecord) {

        AjaxReturnData ajaxReturnData = new AjaxReturnData();

        String memberMobile = healthUserRecord.getMobPhone();
        String checkDate = healthUserRecord.getCheckDateStr();
        Integer orgId = healthUserRecord.getOrgId();
        String pkgUpgrade = healthUserRecord.getPkgUpgrade();
        String pkgType = healthUserRecord.getPkgType();
        String needOptionalOption = healthUserRecord.getNeedOptionalOption();


        // 预约机构信息的取得
        HealthOrg healthOrg = healthOrgMapper.selectByPrimaryKey(orgId);

        // 预约的日期是三天以后的日期
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, healthOrg.getDaysLimit());
        date = calendar.getTime();

        if(DateUtil.toUnixTimeStampByDate(checkDate) < DateUtil.toUnixTimeStampByDate(DateUtil.toDateString(date))) {
            ajaxReturnData.setResult(false);
            ajaxReturnData.setType("1");
            ajaxReturnData.setMessage("预约"+ healthOrg.getOrgName() +"进行体检的话，您预约的体检日期必须是"+ healthOrg.getDaysLimit() +"天以后的日期");
            return ajaxReturnData;
        } else {
            if(DateUtil.toUnixTimeStampByDate(checkDate) == DateUtil.toUnixTimeStampByDate(DateUtil.toDateString(date))) {
                Date dateCheck = new Date();
                Calendar calendarCheck = Calendar.getInstance();
                calendarCheck.setTime(dateCheck);
//                int dayForWeek = 0;
//                if(calendarCheck.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY){
//                    dayForWeek = 7;
//                }else{
//                    dayForWeek = calendarCheck.get(Calendar.DAY_OF_WEEK) - 1;
//                }
//                if(dayForWeek == 5){
//                    //24小时制
//                    if(calendarCheck.get(Calendar.HOUR_OF_DAY) >= 16) {
//                        ajaxReturnData.setResult(false);
//                        ajaxReturnData.setType("1");
//                        ajaxReturnData.setMessage("现在是周五16点以后，只能预约下周二（含）以后的时间");
//                        return ajaxReturnData;
//                    }
//                }
                //24小时制
                if(calendarCheck.get(Calendar.HOUR_OF_DAY) >= 15) {
                    ajaxReturnData.setResult(false);
                    ajaxReturnData.setType("1");
                    ajaxReturnData.setMessage("现在是15点以后，只能预约四天（含）以后的时间");
                    return ajaxReturnData;
                }
            }
        }

        // 是否在预约周期之内
        HealthCycle healthCycle = new HealthCycle();
        healthCycle.setPageSwitch(false);
        healthCycle.setCycleState("1");
        List<HealthCycle> healthCycleList = healthCycleMapper.selectListByCondition(healthCycle);
        if (healthCycleList != null && healthCycleList.size() > 0) {
            for (HealthCycle healthCycleDB : healthCycleList) {
                if (healthCycleDB.getStartDate() <= DateUtil.toUnixTimeStampByDate(checkDate) &&
                        DateUtil.toUnixTimeStampByDate(checkDate) <= healthCycleDB.getEndDate()) {
                    // 在预约周期内
                } else  {
                    ajaxReturnData.setResult(false);
                    ajaxReturnData.setType("2");
                    ajaxReturnData.setMessage("您预约的体检日期必须在当前可预约周期时间内！预约周期："
                            + healthCycleDB.getStartDateStr() + "~" + healthCycleDB.getEndDateStr());
                    return ajaxReturnData;
                }
            }
        } else {
            ajaxReturnData.setResult(false);
            ajaxReturnData.setType("2");
            ajaxReturnData.setMessage("还没有安排体检预约周期，不能进行预约");
            return ajaxReturnData;
        }

        // 该用户有没有需要预约的数据的判断
        HealthUser searchHealthUser =  new  HealthUser();
        searchHealthUser.setMobPhone(memberMobile);
        searchHealthUser.setPageSwitch(false);
        List<HealthUser> searchedList = healthUserMapper.selectListByCondition(searchHealthUser);

        // 体检状态 1:未预约 2:已预约 3:已取消 4:已体检 5:体检完成
        // 各个体检状态的件数
        int state1 = 0;
        int state2 = 0;
        int state3 = 0;
        int state4 = 0;
        int state5 = 0;
        HealthUser noAppointmentUser =  new  HealthUser();

        // 未预约、已取消的数据都可以再预约
        for (HealthUser healthUser :searchedList) {
            if ("1".equals(healthUser.getState())) {
                state1 = state1 + 1;
                noAppointmentUser = healthUser;
            } else if ("2".equals(healthUser.getState())) {
                state2 = state2 + 1;
            } else if ("3".equals(healthUser.getState())) {
                state3 = state3 + 1;
                noAppointmentUser = healthUser;
            } else if ("4".equals(healthUser.getState())) {
                state4 = state4 + 1;
            } else {
                state5 = state5 + 1;
            }
        }

        logger.info("################未预约的体检次数="+state1);
        logger.info("################已预约的体检次数="+state2);
        logger.info("################已取消的体检次数="+state3);
        logger.info("################已体检的体检次数="+state4);
        logger.info("################体检完成的体检次数="+state5);

        // 能否预约、再预约的判断
        if (state1 == 1 || state3 == 1) {
            // 未预约的数据都可以预约
            // 已取消的数据都可以再预约

            // 预约次数的CHECK
            if (noAppointmentUser.getModifyNum() > 1) {
                ajaxReturnData.setResult(false);
                ajaxReturnData.setType("3");
                ajaxReturnData.setMessage("您之前修改的预约次数已经达到两次，如仍需预约，请联系您所在部门的体检负责人。");
                return ajaxReturnData;
            }

            // 预约机构人数CHECK
            // 预约机构满额人数的取得
            HealthOrgAppointment orgAppointment = new HealthOrgAppointment();
            orgAppointment.setOrgId(orgId);
            orgAppointment.setAppointmentDate(DateUtil.toUnixTimeStampByDate(checkDate));
            List<HealthOrgAppointment> orgAppointmentList = appointmentMapper.selectListByCondition(orgAppointment);
            if (orgAppointmentList == null || orgAppointmentList.size() == 0 || orgAppointmentList.size() > 1) {
                ajaxReturnData.setResult(false);
                ajaxReturnData.setType("3");
                ajaxReturnData.setMessage("您预约的体检机构的数据不正确，请联系管理员");
                return ajaxReturnData;
            }
            // 只取一条
            orgAppointment = orgAppointmentList.get(0);

            // 该结构已经预约了的人数的取得
            HealthUserAppointment userAppointment = new HealthUserAppointment();
            userAppointment.setOrgId(orgId);
            userAppointment.setCheckDate(DateUtil.toUnixTimeStampByDate(checkDate));
            userAppointment.setAppointmentedFlg("1");       // 已预约的
            userAppointment.setPageSwitch(false);
            List<HealthUserAppointment>  userAppointmentList = userAppointmentMapper.selectListByCondition(userAppointment);

            if (orgAppointment.getAppointmenterNum() <= userAppointmentList.size()) {
                ajaxReturnData.setResult(false);
                ajaxReturnData.setType("3");
                ajaxReturnData.setMessage("您选择的机构的当天预约名额已满，请选择其它体检机构或其它日期进行预约！");
                return ajaxReturnData;
            }
        } else {
            // 根据手机号只能够取得一条用户数据
            // state1 == 0 && state3 == 0
            if (state2 == 0 && state4 == 0 && state5 == 0) {
                ajaxReturnData.setResult(false);
                ajaxReturnData.setType("3");
                ajaxReturnData.setMessage("您的数据数据还未导入，不能进行预约。请联系管理员");
                return ajaxReturnData;
            } else {
                // state2 == 1
                // 已经有已预约的数据了
                if (state2 > 0) {
                    ajaxReturnData.setResult(false);
                    ajaxReturnData.setType("4");
                    ajaxReturnData.setMessage("您已经预约了体检，请取消后再重新预约");
                    return ajaxReturnData;
                }

                // state4 == 1 || state5 == 1
                ajaxReturnData.setResult(false);
                ajaxReturnData.setType("4");
                ajaxReturnData.setMessage("您预约的体检已经完成，不需要再预约");
                return ajaxReturnData;
            }
        }

        // 更新预约数据
        // 更新HealthUser
        HealthUser healthUser =  healthUserMapper.selectByPrimaryKey(noAppointmentUser.getUserId());
        healthUser.setUserId(noAppointmentUser.getUserId());
        healthUser.setPkgUpgrade(pkgUpgrade);
        healthUser.setPkgType(pkgType);
        // 体检状态 1:未预约 2:已预约 3:已取消 4:已体检 5:体检完成
        healthUser.setState("2");
        if ("1".equals(noAppointmentUser.getState())) {
            // 第一次时不加1
        } else {
            healthUser.setModifyNum(noAppointmentUser.getModifyNum() + 1);
        }
        // 全项目更新
        int updateCount1 = healthUserMapper.updateByPrimaryKey(healthUser);

        // 保存HealthUserAppointment
        HealthUserAppointment userAppointment = new HealthUserAppointment();
        userAppointment.setUserId(noAppointmentUser.getUserId());
        userAppointment.setOrgId(orgId);
        userAppointment.setPkgType(pkgType);
        userAppointment.setBreastCT(healthUserRecord.getBreastCT());
        userAppointment.setRequiredOption(healthUserRecord.getRequiredOption());
        userAppointment.setOptionalOption(healthUserRecord.getOptionalOption());
        userAppointment.setNeedOptionalOption(healthUserRecord.getNeedOptionalOption());
        userAppointment.setPsychologicalAssessmentCheckOption(healthUserRecord.getPsychologicalAssessmentCheckOption());
        userAppointment.setAppointmentTime(DateUtil.unixTimeStampInt().intValue());
        userAppointment.setCheckDate(DateUtil.toUnixTimeStampByDate(checkDate));

        int insertCount1 = userAppointmentMapper.insertSelective(userAppointment);

        // 更新失败时，事物回滚
        if (updateCount1 != 1 || insertCount1 != 1) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            ajaxReturnData.setResult(false);
            ajaxReturnData.setType("5");
            ajaxReturnData.setMessage("预约失败");
            return ajaxReturnData;
        }

        // 预约成功后发短信
        try {
            System.out.println("手机号【" + memberMobile + "】的短信发送开始。。。。。");

            // 对"福临门大厦上门体检"的特殊处理
            if (healthOrg.getOrgName().contains("福临门大厦上门体检")) {
                MemberMsgTpl memberMsgTpl = memberMsgTplMapper.selectByPrimaryKey("health_appointment_suc_car_msg");
                Map<String, Object> smsMap = new HashMap<String, Object>();
                smsMap.put("moblieNumber", memberMobile);
                // 【中粮集团医疗保障室】您已成功预约了航天中心医院福临门大厦上门体检。您的体检日期:{1},体检地点:中粮福临门大厦3011会议室。
                String[] params = new String[1];
                params[0] = checkDate;
                smsMap.put("params", params);

                String mmtShortContent = memberMsgTpl.getMmtShortContent();
                if (StringUtils.contains(pkgType, "D")) {
                    if (StringUtils.equals(needOptionalOption, "是")) {
                        // 【中粮集团医疗保障室】您已成功预约了航天中心医院福临门大厦上门体检。您的体检日期:{1},体检地点:中粮福临门大厦3011会议室。无痛胃肠镜术前，航天中心医院将安排麻醉评估上门服务，请及时关注医院短信通知。如因场地或其他原因造成的变更，将另行通知。
                        mmtShortContent = mmtShortContent + "无痛胃肠镜术前，航天中心医院将安排麻醉评估上门服务，请及时关注医院短信通知。如因场地或其他原因造成的变更，将另行通知。";
                    } else {
                        // 【中粮集团医疗保障室】您已成功预约了航天中心医院福临门大厦上门体检。您的体检日期:{1},体检地点:中粮福临门大厦3011会议室。如因场地或其他原因造成的变更，将另行通知。
                        mmtShortContent = mmtShortContent + "如因场地或其他原因造成的变更，将另行通知。";
                    }
                } else if (StringUtils.contains(pkgType, "C") || StringUtils.contains(pkgType, "B")) {
                    // 【中粮集团医疗保障室】您已成功预约了航天中心医院福临门大厦上门体检。您的体检日期:{1},体检地点:中粮福临门大厦3011会议室。部分体检项目如核磁、冠脉CT、无痛胃肠镜等无法上门完成，可保留项目择期再检。
                    mmtShortContent = mmtShortContent + "部分体检项目如核磁、冠脉CT、无痛胃肠镜等无法上门完成，可保留项目择期再检。";
                }
                memberMsgTpl.setMmtShortContent(mmtShortContent);

                messageAndNoticeService.sendMessageAndNotice(memberMsgTpl, smsMap, null, null, null);
            } else {
                MemberMsgTpl memberMsgTpl = memberMsgTplMapper.selectByPrimaryKey("health_appointment_suc_msg");
                Map<String, Object> smsMap = new HashMap<String, Object>();
                smsMap.put("moblieNumber", memberMobile);
                // 【中粮集团医疗保障室】您已成功预约了{1}的体检。您的体检日期:{2},体检地点:{3}
                String[] params = new String[3];
                params[0] = healthOrg.getOrgName();
                params[1] = checkDate;
                params[2] = healthOrg.getAddress();
                smsMap.put("params", params);
                // 预约成功短信通知时，短信内容要分为包含和不包含“领取体检用品”两类。
                if (healthOrg.getDrawMedicalSuppliesFlg()) {
                    String mmtShortContent = memberMsgTpl.getMmtShortContent();
                    mmtShortContent = mmtShortContent + "（如您需要留便器，可于体检前到医务室领取）";
                    memberMsgTpl.setMmtShortContent(mmtShortContent);
                }

                String mmtShortContent = memberMsgTpl.getMmtShortContent();
                if (StringUtils.contains(pkgType, "D")) {
                    mmtShortContent = mmtShortContent + "，体检当日请携带身份证。";
                } else if (StringUtils.contains(pkgType, "C") || StringUtils.contains(pkgType, "B")) {
                    if (StringUtils.equals(needOptionalOption, "是")) {
                        // 选择"无痛胃肠镜"
                        mmtShortContent = mmtShortContent + "。请携带身份证于体检当日早8：30前到达医院。根据医院相关规定，无痛胃肠镜、冠脉CT项目检查需家属或同事陪同，并签署知情同意书。另请根据体检须知提前停服相关药品。";
                    } else {
                        // 不选择"无痛胃肠镜"
                        mmtShortContent = mmtShortContent + "，体检当日请携带身份证。根据医院相关规定，无痛胃肠镜、冠脉CT项目检查需家属或同事陪同，并签署知情同意书。另请根据体检须知提前停服相关药品。";
                    }
                }
                memberMsgTpl.setMmtShortContent(mmtShortContent);

                messageAndNoticeService.sendMessageAndNotice(memberMsgTpl, smsMap, null, null, null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("手机号【" + memberMobile + "】的短信发送失败：", e);
        } finally {
            System.out.println("手机号【" + memberMobile + "】的短信发送结束。。。。。");
        }

        ajaxReturnData.setResult(true);
        ajaxReturnData.setMessage("预约成功");

        return ajaxReturnData;
    }

    @Override
    @Transactional
    public AjaxReturnData cancelCheckup(String memberMobile, String checkDate) {

        AjaxReturnData ajaxReturnData = new AjaxReturnData();

        // 取得当前用户的预约记录
        HealthUser searchHealthUser =  new  HealthUser();
        searchHealthUser.setMobPhone(memberMobile);
        // 体检状态 1:未预约 2:已预约 3:已取消 4:已体检 5:体检完成
        searchHealthUser.setState("2");   // 取得当前用户的预约记录
        searchHealthUser.setPageSwitch(false);
        List<HealthUser> searchedList = healthUserMapper.selectListByCondition(searchHealthUser);

        if ((searchedList == null) || (searchedList.size() == 0)) {
            ajaxReturnData.setResult(false);
            ajaxReturnData.setType("1");
            ajaxReturnData.setMessage("您没有已预约的数据");
            return ajaxReturnData;
        }

        if (searchedList.size() > 1) {
            ajaxReturnData.setResult(false);
            ajaxReturnData.setType("2");
            ajaxReturnData.setMessage("您已预约的数据不正确，请联系管理员");
            return ajaxReturnData;
        }

        // 是否在预约周期之内
        HealthCycle healthCycle = new HealthCycle();
        healthCycle.setPageSwitch(false);
        healthCycle.setCycleState("1");
        List<HealthCycle> healthCycleList = healthCycleMapper.selectListByCondition(healthCycle);
        if (healthCycleList != null && healthCycleList.size() > 0) {
            for (HealthCycle healthCycleDB : healthCycleList) {
                if (healthCycleDB.getStartDate() <= DateUtil.toUnixTimeStampByDate(checkDate) &&
                        DateUtil.toUnixTimeStampByDate(checkDate) <= healthCycleDB.getEndDate()) {
                    // 在预约周期内
                } else  {
                    ajaxReturnData.setResult(false);
                    ajaxReturnData.setType("3");
                    ajaxReturnData.setMessage("您取消的体检日期必须在当前可预约周期时间内");
                    return ajaxReturnData;
                }
            }
        } else {
            ajaxReturnData.setResult(false);
            ajaxReturnData.setType("3");
            ajaxReturnData.setMessage("还没有安排体检预约周期，不能取消处理");
            return ajaxReturnData;
        }

        // 只取第一条
        HealthUser healthCheckedUser = searchedList.get(0);

        // 根据用户ID，取得当前用的所有预约信息
        HealthUserAppointment searchUserAppointment = new HealthUserAppointment();
        searchUserAppointment.setUserId(healthCheckedUser.getUserId());
        searchUserAppointment.setAppointmentedFlg("1");       // 已预约的
        searchUserAppointment.setPageSwitch(false);
        List<HealthUserAppointment>  userAppointmentList = userAppointmentMapper.selectListByCondition(searchUserAppointment);

        // 最多只会有一条（实际检索条件还需要体检周期）
        HealthUserAppointment userAppointmentDB = null;
        for (HealthUserAppointment userAppointmentDBTemp : userAppointmentList) {
            if (userAppointmentDBTemp.getCheckDate().intValue() == DateUtil.toUnixTimeStampByDate(checkDate)) {
                userAppointmentDB = userAppointmentDBTemp;
                break;
            }
        }
        if (userAppointmentDB == null) {
            ajaxReturnData.setResult(false);
            ajaxReturnData.setType("4");
            ajaxReturnData.setMessage("您预约的数据可能已被取消，请重新预约。");
            return ajaxReturnData;
        }

        // 体检机构取消时间CHECK
        HealthOrgAppointment appointment = new HealthOrgAppointment();
        appointment.setOrgId(userAppointmentDB.getOrgId());
        appointment.setAppointmentDate(userAppointmentDB.getCheckDate());
        List<HealthOrgAppointment> appointmentList = appointmentMapper.selectListByCondition(appointment);
        if (appointmentList == null || appointmentList.size() == 0) {
            ajaxReturnData.setResult(false);
            ajaxReturnData.setType("5");
            ajaxReturnData.setMessage("您已预约的体检机构的数据不正确，请联系管理员");
            return ajaxReturnData;
        }
        if (appointmentList.size() > 1) {
            ajaxReturnData.setResult(false);
            ajaxReturnData.setType("5");
            ajaxReturnData.setMessage("您已预约的体检机构的数据不正确，请联系管理员");
            return ajaxReturnData;
        }
        HealthOrgAppointment orgAppointment = appointmentList.get(0);
        logger.info("orgAppointment.getCancelTime()==" + DateUtil.toIntDate(orgAppointment.getCancelTime()) + "==" + orgAppointment.getCancelTimeStr());
        logger.info("new Date().getTime()==" + new Date() + "==" + DateUtil.toTimeString(new Date()));
        if(DateUtil.toIntDate(orgAppointment.getCancelTime()).before(new Date())) {
            String cancelTime = orgAppointment.getCancelTimeStr();
            ajaxReturnData.setResult(false);
            ajaxReturnData.setType("6");
            ajaxReturnData.setMessage("您的取消时间必须在【"+ cancelTime +"】之前。如果要取消，请联系管理员");
            return ajaxReturnData;
        }

        // 取消处理
        // 更新HealthUser
        HealthUser healthUser = new HealthUser();
        healthUser.setUserId(healthCheckedUser.getUserId());
        // 体检状态 1:未预约 2:已预约 3:已取消 4:已体检 5:体检完成
        healthUser.setState("3");
        int updateCount1 = healthUserMapper.updateByPrimaryKeySelective(healthUser);

        // 更新HealthUserAppointment
        HealthUserAppointment userAppointment = new HealthUserAppointment();
        userAppointment.setUaId(userAppointmentDB.getUaId());
        userAppointment.setCancelTime(DateUtil.unixTimeStampInt().intValue());
        int updateCount2 = userAppointmentMapper.updateByPrimaryKeySelective(userAppointment);

        // 更新失败时，事物回滚
        if (updateCount1 != 1 || updateCount2 != 1) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            ajaxReturnData.setResult(false);
            ajaxReturnData.setType("7");
            ajaxReturnData.setMessage("取消失败");
            return ajaxReturnData;
        }

        // 发短信
        try {
            System.out.println("手机号【" + healthCheckedUser.getMobPhone() + "】的短信发送开始。。。。。");
            MemberMsgTpl memberMsgTpl = memberMsgTplMapper.selectByPrimaryKey("health_appointment_cancel_msg");
            Map<String, Object> smsMap = new HashMap<String, Object>();
            smsMap.put("moblieNumber", healthCheckedUser.getMobPhone());
            // 【中粮集团医疗保障室】您预约的{1}{2}体检已取消，谢谢您的支持。
            String[] params = new String[2];
            HealthOrg healthOrg = healthOrgMapper.selectByPrimaryKey(userAppointmentDB.getOrgId());
            params[0] = healthOrg.getOrgName();
            params[1] = userAppointmentDB.getCheckDateStr();
            smsMap.put("params", params);
            messageAndNoticeService.sendMessageAndNotice(memberMsgTpl, smsMap, null, null, null);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("手机号【" + healthUser.getMobPhone() + "】的短信发送失败：", e);
        } finally {
            System.out.println("手机号【" + healthUser.getMobPhone() + "】的短信发送结束。。。。。");
        }

        ajaxReturnData.setResult(true);
        ajaxReturnData.setMessage("取消成功");

        return ajaxReturnData;
    }

    @Override
    public void batchSetRemindMsg(){
        HealthUser healthUser = new HealthUser();
        healthUser.setPageSwitch(false);
        // 体检状态 1:未预约 2:已预约 3:已取消 4:已体检 5:体检完成
        healthUser.setState("2");
        List<HealthUser> healthUserList= healthUserMapper.selectListByCondition(healthUser);
        Date date = new Date();
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(Calendar.DATE,1);
        date = calendar.getTime();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(date);

        HealthUserAppointment healthUserAppointment = new HealthUserAppointment();

        for(int i = 0; i<healthUserList.size(); i++){
            healthUser = healthUserList.get(i);
            healthUserAppointment.setUserId(healthUser.getUserId());

            List<HealthUserAppointment> healthUserAppointmentList = userAppointmentMapper.selectListByCondition(healthUserAppointment);

            for(int j = 0; j<healthUserAppointmentList.size(); j++) {
                if ((dateString.equals(healthUserAppointmentList.get(j).getCheckDateStr())) && healthUserAppointmentList.get(j).getCancelTime() == null) {
                    try {
                        System.out.println("手机号【" + healthUser.getMobPhone() + "】的短信发送开始。。。。。");
                        MemberMsgTpl memberMsgTpl = memberMsgTplMapper.selectByPrimaryKey("health_remind_msg");
                        Map<String, Object> smsMap = new HashMap<String, Object>();
                        smsMap.put("moblieNumber", healthUser.getMobPhone());
                        // 【中粮集团医疗保障室】{1}您好，请您于明天（{2}），到{3}（{4}）进行体检。
                        String[] params = new String[4];
                        params[0] = healthUser.getUserName();
                        params[1] = healthUserAppointmentList.get(j).getCheckDateStr();
                        HealthOrg healthOrg = healthOrgMapper.selectByPrimaryKey(healthUserAppointmentList.get(j).getOrgId());
                        params[2] = healthOrg.getOrgName();
                        params[3] = healthOrg.getAddress();
                        smsMap.put("params", params);
                        // 预约成功短信通知时，短信内容要分为包含和不包含“领取体检用品”两类。
                        if (healthOrg.getDrawMedicalSuppliesFlg()) {
                            String mmtShortContent = memberMsgTpl.getMmtShortContent();
                            mmtShortContent = mmtShortContent + "（如您需要留便器，可于体检前到医务室领取）";
                            memberMsgTpl.setMmtShortContent(mmtShortContent);
                        }
                        messageAndNoticeService.sendMessageAndNotice(memberMsgTpl, smsMap, null, null, null);
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.error("手机号【" + healthUser.getMobPhone() + "】的短信发送失败：", e);
                    } finally {
                        System.out.println("手机号【" + healthUser.getMobPhone() + "】的短信发送结束。。。。。");
                    }
                }
            }
        }
    }

    @Override
    @Transactional
    public void changePkgTypeBySchedule() {
        HealthUser healthUser = new HealthUser();
        healthUser.setPageSwitch(false);
        // 体检状态 1:未预约 2:已预约 3:已取消 4:已体检 5:体检完成
        healthUser.setState("1");
        List<HealthUser> healthUserList= healthUserMapper.selectListByCondition(healthUser);

        for (HealthUser element : healthUserList) {
            int age = CalculateUserAgeUtils.calculate(element.getCardId(), new Date());
            if (element.getUserAge() < 40 && age >= 40) {
                HealthUser updateHealthUser = new HealthUser();
                updateHealthUser.setUserId(element.getUserId());
                updateHealthUser.setUserAge(age);
                if (element.getPkgType().equals("C1")) {
                    updateHealthUser.setPkgType("C3");
                } else if (element.getPkgType().equals("C2")) {
                    updateHealthUser.setPkgType("C4");
                } else if (element.getPkgType().equals("D1")) {
                    updateHealthUser.setPkgType("D3");
                } else if (element.getPkgType().equals("D2")) {
                    updateHealthUser.setPkgType("D4");
                } else {
                    continue;
                }

                healthUserMapper.updateByPrimaryKeySelective(updateHealthUser);
            }
        }
    }

    @Override
    @Transactional
    public AjaxReturnData reportGetList(List<HealthUser> healthUserList) {
        AjaxReturnData ajaxReturnData = new AjaxReturnData();

        //手机号检查
        HealthUser healthUser = null;
        for (int i = 0; i<healthUserList.size(); i++) {
            healthUser = healthUserList.get(i);

            healthUser.setPageSwitch(false);
            List<HealthUser> healthUserList1 = healthUserMapper.selectListByCondition(healthUser);

            // 手机号相同的数据没有
            if ((healthUserList1 == null) || (healthUserList1.size() == 0)) {
                // 数据库内没有该手机号数据
                ajaxReturnData.setResult(false);
                ajaxReturnData.setMessage("手机号为" + healthUser.getMobPhone() + "的用户不存在！");
                return ajaxReturnData;
            } else {
                // 不处理
            }

            // 2019-07: 将发送体检报告通知与状态关联去掉（目前是只有“已预约”状态才能发送体检报告通知）。
//            HealthUser healthUser1 = healthUserList1.get(0);
//            // 预约状态是否为已预约
//            if (!"2".equals(healthUser1.getState())) {
//                // 数据库内没有该手机号数据
//                ajaxReturnData.setResult(false);
//                ajaxReturnData.setMessage("手机号为" + healthUser1.getMobPhone() + "的用户不是已预约状态，不能通知！");
//                return ajaxReturnData;
//            } else {
//                // 不处理
//            }
        }

        for (int i = 0; i<healthUserList.size(); i++) {
            healthUser = healthUserList.get(i);

            healthUser.setPageSwitch(false);
            List<HealthUser> healthUserList1 = healthUserMapper.selectListByCondition(healthUser);
            HealthUser healthUser1 = healthUserList1.get(0);

            try {
                System.out.println("手机号【" + healthUser1.getMobPhone() + "】的短信发送开始。。。。。");
                MemberMsgTpl memberMsgTpl = memberMsgTplMapper.selectByPrimaryKey("health_report_get_msg");
                Map<String, Object> smsMap = new HashMap<String, Object>();
                smsMap.put("moblieNumber", healthUser1.getMobPhone());
                // 【中粮集团医疗保障室】{1}您好，您的体检报告已经到达中粮集团医疗保障室（福临门大厦东门外医务室）。
                String[] params = new String[1];
                params[0] = healthUser1.getUserName();
                smsMap.put("params", params);
                messageAndNoticeService.sendMessageAndNotice(memberMsgTpl, smsMap, null, null, null);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("手机号【" + healthUser1.getMobPhone() + "】的短信发送失败：", e);
            } finally {
                System.out.println("手机号【" + healthUser1.getMobPhone() + "】的短信发送结束。。。。。");
            }

            healthUser1.setState("5");
            healthUserMapper.updateByPrimaryKeySelective(healthUser1);
        }

        ajaxReturnData.setResult(true);
        ajaxReturnData.setMessage("通知成功");

        return ajaxReturnData;
    }

    @Override
    public AjaxReturnData reportGet(Integer userId) {
        AjaxReturnData ajaxReturnData = new AjaxReturnData();

        HealthUser healthUser = healthUserMapper.selectByPrimaryKey(userId);

        try {
            System.out.println("手机号【" + healthUser.getMobPhone() + "】的短信发送开始。。。。。");
            MemberMsgTpl memberMsgTpl = memberMsgTplMapper.selectByPrimaryKey("health_report_get_msg");
            Map<String, Object> smsMap = new HashMap<String, Object>();
            smsMap.put("moblieNumber", healthUser.getMobPhone());
            // 【中粮集团医疗保障室】{1}您好，您的体检报告已经到达中粮集团医疗保障室（福临门大厦东门外医务室）。
            String[] params = new String[1];
            params[0] = healthUser.getUserName();
            smsMap.put("params", params);
            messageAndNoticeService.sendMessageAndNotice(memberMsgTpl, smsMap, null, null, null);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("手机号【" + healthUser.getMobPhone() + "】的短信发送失败：", e);
        } finally {
            System.out.println("手机号【" + healthUser.getMobPhone() + "】的短信发送结束。。。。。");
        }

        healthUser.setState("5");
        healthUserMapper.updateByPrimaryKeySelective(healthUser);

        ajaxReturnData.setResult(true);
        ajaxReturnData.setMessage("通知成功");

        return ajaxReturnData;
    }

    @Override
    @Transactional
    public boolean insertUserAndUserAppointment(HealthUser healthUser, HealthUserAppointment vmHuaInfo) {
        //更新结果判定
        int userResult = 0;
        int userHuaResult = 0;
        //选择体检机构或者选择体检时间
        if (vmHuaInfo.getOrgId() != null) {
            //预约状态：已预约
            healthUser.setState("2");
            //更新用户信息
            userResult = healthUserMapper.insertSelective(healthUser);
            //预约信息
            vmHuaInfo.setUserId(healthUser.getUserId());
            vmHuaInfo.setAppointmentTime(DateUtil.unixTimeStampInt().intValue());
            vmHuaInfo.setCheckDate(DateUtil.toUnixTimeStampByDate(vmHuaInfo.getCheckDateStr()));
            userHuaResult = userAppointmentMapper.insertSelective(vmHuaInfo);
        } else {
            //更新用户信息
            userResult = healthUserMapper.insertSelective(healthUser);
            //预约信息没有修改，无更新处理
            userHuaResult = 2;
        }
        if (userResult > 0 && userHuaResult > 0) {
            if (userHuaResult == 1) {
                // 预约成功后发短信
                try {
                    System.out.println("手机号【" + healthUser.getMobPhone() + "】的短信发送开始。。。。。");
                    //取得体检机构信息
                    HealthOrg healthOrg = healthOrgMapper.selectByPrimaryKey(vmHuaInfo.getOrgId());

                    // 对"福临门大厦上门体检"的特殊处理
                    if (healthOrg.getOrgName().contains("福临门大厦上门体检")) {
                        MemberMsgTpl memberMsgTpl = memberMsgTplMapper.selectByPrimaryKey("health_appointment_suc_car_msg");
                        Map<String, Object> smsMap = new HashMap<String, Object>();
                        smsMap.put("moblieNumber", healthUser.getMobPhone());
                        // 【中粮集团医疗保障室】您已成功预约了航天中心医院福临门大厦上门体检。您的体检日期:{1},体检地点:中粮福临门大厦3011会议室。
                        String[] params = new String[1];
                        params[0] = vmHuaInfo.getCheckDateStr();
                        smsMap.put("params", params);

                        String mmtShortContent = memberMsgTpl.getMmtShortContent();
                        if (StringUtils.contains(healthUser.getPkgType(), "D")) {
                            if (StringUtils.equals(vmHuaInfo.getNeedOptionalOption(), "是")) {
                                // 【中粮集团医疗保障室】您已成功预约了航天中心医院福临门大厦上门体检。您的体检日期:{1},体检地点:中粮福临门大厦3011会议室。无痛胃肠镜术前，航天中心医院将安排麻醉评估上门服务，请及时关注医院短信通知。如因场地或其他原因造成的变更，将另行通知。
                                mmtShortContent = mmtShortContent + "无痛胃肠镜术前，航天中心医院将安排麻醉评估上门服务，请及时关注医院短信通知。如因场地或其他原因造成的变更，将另行通知。";
                            } else {
                                // 【中粮集团医疗保障室】您已成功预约了航天中心医院福临门大厦上门体检。您的体检日期:{1},体检地点:中粮福临门大厦3011会议室。如因场地或其他原因造成的变更，将另行通知。
                                mmtShortContent = mmtShortContent + "如因场地或其他原因造成的变更，将另行通知。";
                            }
                        } else if (StringUtils.contains(healthUser.getPkgType(), "C") || StringUtils.contains(healthUser.getPkgType(), "B")) {
                            // 【中粮集团医疗保障室】您已成功预约了航天中心医院福临门大厦上门体检。您的体检日期:{1},体检地点:中粮福临门大厦3011会议室。部分体检项目如核磁、冠脉CT、无痛胃肠镜等无法上门完成，可保留项目择期再检。
                            mmtShortContent = mmtShortContent + "部分体检项目如核磁、冠脉CT、无痛胃肠镜等无法上门完成，可保留项目择期再检。";
                        }
                        memberMsgTpl.setMmtShortContent(mmtShortContent);

                        messageAndNoticeService.sendMessageAndNotice(memberMsgTpl, smsMap, null, null, null);
                    } else {
                        MemberMsgTpl memberMsgTpl = memberMsgTplMapper.selectByPrimaryKey("health_appointment_suc_msg");
                        Map<String, Object> smsMap = new HashMap<String, Object>();
                        smsMap.put("moblieNumber", healthUser.getMobPhone());
                        // 【中粮集团医疗保障室】您已成功预约了{1}的体检。您的体检日期:{2},体检地点:{3}
                        String[] params = new String[3];
                        params[0] = healthOrg.getOrgName();
                        params[1] = vmHuaInfo.getCheckDateStr();
                        params[2] = healthOrg.getAddress();
                        smsMap.put("params", params);
                        // 预约成功短信通知时，短信内容要分为包含和不包含“领取体检用品”两类。
                        if (healthOrg.getDrawMedicalSuppliesFlg()) {
                            String mmtShortContent = memberMsgTpl.getMmtShortContent();
                            mmtShortContent = mmtShortContent + "（如您需要留便器，可于体检前到医务室领取）";
                            memberMsgTpl.setMmtShortContent(mmtShortContent);
                        }

                        String mmtShortContent = memberMsgTpl.getMmtShortContent();
                        if (StringUtils.contains(healthUser.getPkgType(), "D")) {
                            mmtShortContent = mmtShortContent + "，体检当日请携带身份证。";
                        } else if (StringUtils.contains(healthUser.getPkgType(), "C") || StringUtils.contains(healthUser.getPkgType(), "B")) {
                            if (StringUtils.equals(vmHuaInfo.getNeedOptionalOption(), "是")) {
                                // 选择"无痛胃肠镜"
                                mmtShortContent = mmtShortContent + "。请携带身份证于体检当日早8：30前到达医院。根据医院相关规定，无痛胃肠镜、冠脉CT项目检查需家属或同事陪同，并签署知情同意书。另请根据体检须知提前停服相关药品。";
                            } else {
                                // 不选择"无痛胃肠镜"
                                mmtShortContent = mmtShortContent + "，体检当日请携带身份证。根据医院相关规定，无痛胃肠镜、冠脉CT项目检查需家属或同事陪同，并签署知情同意书。另请根据体检须知提前停服相关药品。";
                            }
                        }
                        memberMsgTpl.setMmtShortContent(mmtShortContent);

                        messageAndNoticeService.sendMessageAndNotice(memberMsgTpl, smsMap, null, null, null);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("手机号【" + healthUser.getMobPhone() + "】的短信发送失败：", e);
                } finally {
                    System.out.println("手机号【" + healthUser.getMobPhone() + "】的短信发送结束。。。。。");
                }
            }
            return true;
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }

    @Override
    @Transactional
    public boolean updateUserAndUserAppointment(HealthUser healthUser, HealthUserAppointment vmHuaInfo) {
        //更新结果判定
        int userResult = 0;
        int userHuaResult = 0;
        int cancelRes = 0;
        Integer cancelOrgId = 0;
        String cancelCheckDate = "";

        // 次数修改为0， 状态设为未预约时
        if ("1".equals(healthUser.getState())) {
            // 只更新用户表
            //预约状态：已预约
            healthUser.setState("1");
            //更新用户信息
            userResult = healthUserMapper.updateByPrimaryKey(healthUser);
            //预约信息没有修改，无更新处理
            userHuaResult = 2;
        } else if (vmHuaInfo.getUaId() == null) {
            //未预约过
            //选择体检机构或者选择体检时间
            if (vmHuaInfo.getOrgId() != null) {
                //预约状态：已预约
                healthUser.setState("2");
                //更新用户信息
                userResult = healthUserMapper.updateByPrimaryKey(healthUser);
                //预约信息
                HealthUserAppointment insertHua = new HealthUserAppointment();
                insertHua.setUserId(healthUser.getUserId());
                insertHua.setOrgId(vmHuaInfo.getOrgId());
                insertHua.setPkgType(healthUser.getPkgType());
                insertHua.setBreastCT(vmHuaInfo.getBreastCT());
                insertHua.setRequiredOption(vmHuaInfo.getRequiredOption());
                insertHua.setOptionalOption(vmHuaInfo.getOptionalOption());
                insertHua.setNeedOptionalOption(vmHuaInfo.getNeedOptionalOption());
                insertHua.setPsychologicalAssessmentCheckOption(vmHuaInfo.getPsychologicalAssessmentCheckOption());
                insertHua.setAppointmentTime(DateUtil.unixTimeStampInt().intValue());
                insertHua.setCheckDate(DateUtil.toUnixTimeStampByDate(vmHuaInfo.getCheckDateStr()));
                userHuaResult = userAppointmentMapper.insertSelective(insertHua);
            } else {
                //更新用户信息
                userResult = healthUserMapper.updateByPrimaryKey(healthUser);
                //预约信息没有修改，无更新处理
                userHuaResult = 2;
            }
        } else {
            // 预约过
            //查询DB预约信息
            HealthUserAppointment dbHuaInfo = userAppointmentMapper.selectByPrimaryKey(vmHuaInfo.getUaId());
            //预约信息
            if ("2".equals(healthUser.getState())) {
                //更新用户信息（使用页面的数据）
                userResult = healthUserMapper.updateByPrimaryKey(healthUser);
                if (dbHuaInfo.getCancelTime() == null) {
                    //体检机构修改或者体检时间修改
                    if (vmHuaInfo.getOrgId().intValue() != dbHuaInfo.getOrgId().intValue() ||
                            !vmHuaInfo.getPkgType().equals(dbHuaInfo.getPkgType()) ||
                            !StringUtils.equals(vmHuaInfo.getBreastCT(), dbHuaInfo.getBreastCT()) ||
                            !StringUtils.equals(vmHuaInfo.getRequiredOption(), dbHuaInfo.getRequiredOption()) ||
                            !StringUtils.equals(vmHuaInfo.getOptionalOption(), dbHuaInfo.getOptionalOption()) ||
                            !StringUtils.equals(vmHuaInfo.getNeedOptionalOption(), dbHuaInfo.getNeedOptionalOption()) ||
                            !StringUtils.equals(vmHuaInfo.getPsychologicalAssessmentCheckOption(), dbHuaInfo.getPsychologicalAssessmentCheckOption()) ||
                            !vmHuaInfo.getCheckDateStr().equals(dbHuaInfo.getCheckDateStr())) {
                        //先查询要取消的该条预约信息的体检机构和体检时间
                        HealthUserAppointment dbCancelHua = userAppointmentMapper.selectByPrimaryKey(vmHuaInfo.getUaId());
                        cancelOrgId = dbCancelHua.getOrgId();
                        cancelCheckDate = dbCancelHua.getCheckDateStr();
                        //先取消
                        HealthUserAppointment cancelHua = new HealthUserAppointment();
                        cancelHua.setUaId(vmHuaInfo.getUaId());
                        cancelHua.setCancelTime(DateUtil.unixTimeStampInt().intValue());
                        cancelRes = userAppointmentMapper.updateByPrimaryKeySelective(cancelHua);
                        if (cancelRes > 0) {
                            //再插入一条新的预约
                            HealthUserAppointment insertHua = new HealthUserAppointment();
                            insertHua.setUserId(healthUser.getUserId());
                            insertHua.setOrgId(vmHuaInfo.getOrgId());
                            insertHua.setPkgType(healthUser.getPkgType());
                            insertHua.setBreastCT(vmHuaInfo.getBreastCT());
                            insertHua.setRequiredOption(vmHuaInfo.getRequiredOption());
                            insertHua.setOptionalOption(vmHuaInfo.getOptionalOption());
                            insertHua.setNeedOptionalOption(vmHuaInfo.getNeedOptionalOption());
                            insertHua.setPsychologicalAssessmentCheckOption(vmHuaInfo.getPsychologicalAssessmentCheckOption());
                            insertHua.setAppointmentTime(DateUtil.unixTimeStampInt().intValue());
                            insertHua.setCheckDate(DateUtil.toUnixTimeStampByDate(vmHuaInfo.getCheckDateStr()));
                            userHuaResult = userAppointmentMapper.insertSelective(insertHua);
                        }
                    } else {
                        //预约信息没有修改，无更新处理
                        userHuaResult = 2;
                    }
                } else {
                    //刚取消完，插入一条新预约
                    HealthUserAppointment insertHua = new HealthUserAppointment();
                    insertHua.setUserId(healthUser.getUserId());
                    insertHua.setOrgId(vmHuaInfo.getOrgId());
                    insertHua.setPkgType(healthUser.getPkgType());
                    insertHua.setBreastCT(vmHuaInfo.getBreastCT());
                    insertHua.setRequiredOption(vmHuaInfo.getRequiredOption());
                    insertHua.setOptionalOption(vmHuaInfo.getOptionalOption());
                    insertHua.setNeedOptionalOption(vmHuaInfo.getNeedOptionalOption());
                    insertHua.setPsychologicalAssessmentCheckOption(vmHuaInfo.getPsychologicalAssessmentCheckOption());
                    insertHua.setCheckDate(DateUtil.toUnixTimeStampByDate(vmHuaInfo.getCheckDateStr()));
                    insertHua.setAppointmentTime(DateUtil.unixTimeStampInt().intValue());
                    userHuaResult = userAppointmentMapper.insertSelective(insertHua);
                }
            } else {
                //体检状态为已取消
                if ("3".equals(healthUser.getState())) {
                    // 更新用户信息
                    // 取消时，只更新用户的状态。其他值都不更新 （不能用页面的数据）
                    HealthUser healthUserDB = healthUserMapper.selectByPrimaryKey(healthUser.getUserId());
                    healthUserDB.setState("3");
                    userResult = healthUserMapper.updateByPrimaryKey(healthUserDB);

                    // 取消前的数据（不能用页面的数据）
                    cancelOrgId = dbHuaInfo.getOrgId();
                    cancelCheckDate = dbHuaInfo.getCheckDateStr();
                    //体检状态由已预约->已取消
                    if (dbHuaInfo.getCancelTime() == null) {
                        // 取消原来的数据（不能用页面的数据）
                        dbHuaInfo.setCancelTime(DateUtil.unixTimeStampInt().intValue());
                        userHuaResult = userAppointmentMapper.updateByPrimaryKeySelective(dbHuaInfo);
                    } else {
                        //预约信息没有修改，无更新处理
                        userHuaResult = 2;
                    }
                }
            }
        }
        if (userResult > 0 && userHuaResult > 0) {
            if (userHuaResult == 1) {
                //取得体检机构信息
                HealthOrg healthOrg = healthOrgMapper.selectByPrimaryKey(vmHuaInfo.getOrgId());
                try {
                    //预约成功后发短信
                    if ("2".equals(healthUser.getState())) {
                        System.out.println("手机号【" + healthUser.getMobPhone() + "】的短信发送开始。。。。。");
                        if (cancelRes == 1) {
                            //取得取消体检机构信息
                            HealthOrg cancelHealthOrg = healthOrgMapper.selectByPrimaryKey(cancelOrgId);
                            //取消成功短信模板取得
                            MemberMsgTpl memberMsgTpl = memberMsgTplMapper.selectByPrimaryKey("health_appointment_cancel_msg");
                            Map<String, Object> smsMap = new HashMap<String, Object>();
                            smsMap.put("moblieNumber", healthUser.getMobPhone());
                            // 【中粮集团医疗保障室】您预约的{1}{2}体检已取消，谢谢您的支持。
                            String[] params = new String[2];
                            params[0] = cancelHealthOrg.getOrgName();
                            params[1] = cancelCheckDate;
                            smsMap.put("params", params);
                            messageAndNoticeService.sendMessageAndNotice(memberMsgTpl, smsMap, null, null, null);
                        }
                        //预约成功短信模板取得
                        // 对"福临门大厦上门体检"的特殊处理
                        if (healthOrg.getOrgName().contains("福临门大厦上门体检")) {
                            MemberMsgTpl memberMsgTpl = memberMsgTplMapper.selectByPrimaryKey("health_appointment_suc_car_msg");
                            Map<String, Object> smsMap = new HashMap<String, Object>();
                            smsMap.put("moblieNumber", healthUser.getMobPhone());
                            // 【中粮集团医疗保障室】您已成功预约了航天中心医院福临门大厦上门体检。您的体检日期:{1},体检地点:中粮福临门大厦3011会议室。
                            String[] params = new String[1];
                            params[0] = vmHuaInfo.getCheckDateStr();
                            smsMap.put("params", params);

                            String mmtShortContent = memberMsgTpl.getMmtShortContent();
                            if (StringUtils.contains(healthUser.getPkgType(), "D")) {
                                if (StringUtils.equals(vmHuaInfo.getNeedOptionalOption(), "是")) {
                                    // 【中粮集团医疗保障室】您已成功预约了航天中心医院福临门大厦上门体检。您的体检日期:{1},体检地点:中粮福临门大厦3011会议室。无痛胃肠镜术前，航天中心医院将安排麻醉评估上门服务，请及时关注医院短信通知。如因场地或其他原因造成的变更，将另行通知。
                                    mmtShortContent = mmtShortContent + "无痛胃肠镜术前，航天中心医院将安排麻醉评估上门服务，请及时关注医院短信通知。如因场地或其他原因造成的变更，将另行通知。";
                                } else {
                                    // 【中粮集团医疗保障室】您已成功预约了航天中心医院福临门大厦上门体检。您的体检日期:{1},体检地点:中粮福临门大厦3011会议室。如因场地或其他原因造成的变更，将另行通知。
                                    mmtShortContent = mmtShortContent + "如因场地或其他原因造成的变更，将另行通知。";
                                }
                            } else if (StringUtils.contains(healthUser.getPkgType(), "C") || StringUtils.contains(healthUser.getPkgType(), "B")) {
                                // 【中粮集团医疗保障室】您已成功预约了航天中心医院福临门大厦上门体检。您的体检日期:{1},体检地点:中粮福临门大厦3011会议室。部分体检项目如核磁、冠脉CT、无痛胃肠镜等无法上门完成，可保留项目择期再检。
                                mmtShortContent = mmtShortContent + "部分体检项目如核磁、冠脉CT、无痛胃肠镜等无法上门完成，可保留项目择期再检。";
                            }
                            memberMsgTpl.setMmtShortContent(mmtShortContent);

                            messageAndNoticeService.sendMessageAndNotice(memberMsgTpl, smsMap, null, null, null);
                        } else {
                            MemberMsgTpl memberMsgTpl = memberMsgTplMapper.selectByPrimaryKey("health_appointment_suc_msg");
                            Map<String, Object> smsMap = new HashMap<String, Object>();
                            smsMap.put("moblieNumber", healthUser.getMobPhone());
                            // 【中粮集团医疗保障室】您已成功预约了{1}的体检。您的体检日期:{2},体检地点:{3}
                            String[] params = new String[3];
                            params[0] = healthOrg.getOrgName();
                            params[1] = vmHuaInfo.getCheckDateStr();
                            params[2] = healthOrg.getAddress();
                            smsMap.put("params", params);
                            // 预约成功短信通知时，短信内容要分为包含和不包含“领取体检用品”两类。
                            if (healthOrg.getDrawMedicalSuppliesFlg()) {
                                String mmtShortContent = memberMsgTpl.getMmtShortContent();
                                mmtShortContent = mmtShortContent + "（如您需要留便器，可于体检前到医务室领取）";
                                memberMsgTpl.setMmtShortContent(mmtShortContent);
                            }

                            String mmtShortContent = memberMsgTpl.getMmtShortContent();
                            if (StringUtils.contains(healthUser.getPkgType(), "D")) {
                                mmtShortContent = mmtShortContent + "，体检当日请携带身份证。";
                            } else if (StringUtils.contains(healthUser.getPkgType(), "C") || StringUtils.contains(healthUser.getPkgType(), "B")) {
                                if (StringUtils.equals(vmHuaInfo.getNeedOptionalOption(), "是")) {
                                    // 选择"无痛胃肠镜"
                                    mmtShortContent = mmtShortContent + "。请携带身份证于体检当日早8：30前到达医院。根据医院相关规定，无痛胃肠镜、冠脉CT项目检查需家属或同事陪同，并签署知情同意书。另请根据体检须知提前停服相关药品。";
                                } else {
                                    // 不选择"无痛胃肠镜"
                                    mmtShortContent = mmtShortContent + "，体检当日请携带身份证。根据医院相关规定，无痛胃肠镜、冠脉CT项目检查需家属或同事陪同，并签署知情同意书。另请根据体检须知提前停服相关药品。";
                                }
                            }
                            memberMsgTpl.setMmtShortContent(mmtShortContent);

                            messageAndNoticeService.sendMessageAndNotice(memberMsgTpl, smsMap, null, null, null);
                        }
                    } else {
                        //取消成功后发短信
                        if ("3".equals(healthUser.getState())) {
                            //取得取消体检机构信息
                            HealthOrg cancelHealthOrg = healthOrgMapper.selectByPrimaryKey(cancelOrgId);
                            System.out.println("手机号【" + healthUser.getMobPhone() + "】的短信发送开始。。。。。");
                            //取消成功短信模板取得
                            MemberMsgTpl memberMsgTpl = memberMsgTplMapper.selectByPrimaryKey("health_appointment_cancel_msg");
                            Map<String, Object> smsMap = new HashMap<String, Object>();
                            smsMap.put("moblieNumber", healthUser.getMobPhone());
                            // 【中粮集团医疗保障室】您预约的{1}{2}体检已取消，谢谢您的支持。
                            String[] params = new String[2];
                            params[0] = cancelHealthOrg.getOrgName();
                            params[1] = vmHuaInfo.getCheckDateStr();
                            smsMap.put("params", params);
                            messageAndNoticeService.sendMessageAndNotice(memberMsgTpl, smsMap, null, null, null);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("手机号【" + healthUser.getMobPhone() + "】的短信发送失败：", e);
                } finally {
                    System.out.println("手机号【" + healthUser.getMobPhone() + "】的短信发送结束。。。。。");
                }
            }
            return true;
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }
}
